package com.photoeditor.demo.ui.adapter.home;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.photoeditor.R;
import com.photoeditor.demo.db.FunctionCardInfoBean;

import java.util.ArrayList;

public class FunctionCardAdapter extends RecyclerView.Adapter<FunctionCardAdapter.FunctionCardViewHolder> {
    private Context context;
    private ArrayList<FunctionCardInfoBean> infos;

    public FunctionCardAdapter(Context context,ArrayList<FunctionCardInfoBean> infos) {
        this.context=context;
        this.infos=infos;
    }

    @Override
    public FunctionCardAdapter.FunctionCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new FunctionCardViewHolder(LayoutInflater.from(context).inflate(R.layout.item_function_card, parent,false));

    }

    @Override
    public void onBindViewHolder(FunctionCardAdapter.FunctionCardViewHolder holder, int position) {
        holder.icon.setImageDrawable(infos.get(position).getDrawable());
        holder.title.setText(infos.get(position).getTitie());
    }

    @Override
    public int getItemCount() {
        return infos == null ? 0 : infos.size();
    }

    class FunctionCardViewHolder extends RecyclerView.ViewHolder {
        ImageView icon;
        TextView title;

        public FunctionCardViewHolder(@NonNull View itemView) {
            super(itemView);
            icon=itemView.findViewById(R.id.iv_icon);
            title=itemView.findViewById(R.id.tv_title);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mOnItemClickListener != null) {
                        int position = getAdapterPosition();
                        //确保position值有效
                        if (position != RecyclerView.NO_POSITION) {
                            mOnItemClickListener.onItemClicked(view, position);
                        }
                    }
                }
            });
        }
    }

    private OnItemClickListener mOnItemClickListener;

    public interface OnItemClickListener {
        void onItemClicked(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener clickListener) {
        this.mOnItemClickListener = clickListener;
    }


}
